package com.github.byakkili.bim.core.cluster;

import cn.hutool.core.map.MapUtil;
import com.github.byakkili.bim.core.BimContext;
import lombok.Getter;
import lombok.Setter;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Guannian Li
 */
@Getter
public abstract class AbstractClusterManager implements ClusterManager {
    /**
     * B-IM 上下文
     */
    private @Setter BimContext context;
    /**
     * 集群处理器
     */
    private final Map<String, ClusterProcessor<BaseClusterPacket>> clusterProcessors = new ConcurrentHashMap<>();

    @Override
    public final boolean send(BaseClusterPacket clusterPacket) {
        clusterPacket.setFromServerId(context.getServerId());
        return doSend(clusterPacket);
    }

    /**
     * 发送包到集群
     */
    protected abstract boolean doSend(BaseClusterPacket clusterPacket);

    /**
     * 接收集群数据包
     */
    protected final void doReceive(BaseClusterPacket packet) {
        if (MapUtil.isEmpty(clusterProcessors) || packet == null) {
            return;
        }
        ClusterProcessor<BaseClusterPacket> handler = clusterProcessors.get(packet.getClass().getName());
        if (handler != null) {
            handler.handle(packet, context);
        }
    }

    /**
     * 添加集群处理器
     */
    public final void addClusterProcessor(ClusterProcessor<? extends BaseClusterPacket> clusterProcessor) {
        @SuppressWarnings("unchecked")
        ClusterProcessor<BaseClusterPacket> processor = (ClusterProcessor<BaseClusterPacket>) clusterProcessor;
        clusterProcessors.put(clusterProcessor.packetClass().getName(), processor);
    }
}
